﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        //private InventoryDataContext _context = new InventoryDataContext(WpfApplication1.Properties.Settings.Default.SalesManagerConnectionString);
        private SalesManagerEntities _context = new SalesManagerEntities();
        private CollectionViewSource _productGroupViewSource;// = new CollectionViewSource();
        private CollectionViewSource _productViewSource;
        private CollectionViewSource _productComponentViewSource;
        private CollectionViewSource _isAProductListViewSource;
        private CollectionViewSource _resultantProductPricing;
        public int OwnerID = 1;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _productGroupViewSource = (CollectionViewSource)FindResource("ProductGroup");
            _productGroupViewSource.Source = from c in _context.tblProductGroups 
                                             where c.Active 
                                                && c.OwnerID == OwnerID
                                             orderby c.ShortName
                                             select new {c.ProductGroupID, c.ShortName, c.tblProducts};
            _productGroupViewSource.View.CurrentChanged += new EventHandler(ProductGroup_CurrentChanged);

            _productViewSource = (CollectionViewSource)FindResource("Products");
            _productViewSource.View.CurrentChanged += new EventHandler(Product_CurrentChanged);

            _resultantProductPricing = (CollectionViewSource)FindResource("ResultantProductPricing");

            // Build the pricing class selection list with a null value added in
            var pricingClassList = (from c in _context.codeProductPricingClasses
                                    where c.OwnerID == OwnerID
                                    select new { ProductPricingClassCode = (char?)c.ProductPricingClassCode, c.Description }).ToList();
            pricingClassList.Add(new {ProductPricingClassCode=(char?)null, Description=String.Empty});
            ((CollectionViewSource)FindResource("PricingCodes")).Source = pricingClassList;

            // Build the promotion selection list with a null value added in.
            var promotionList = (from c in _context.tblPromotions
                                 where c.OwnerID == OwnerID
                                    && c.Active
                                 select new { PromotionID = (int?)c.PromotionID, c.Description }).ToList();
            promotionList.Add(new { PromotionID = (int?)null, Description = String.Empty });
            ((CollectionViewSource)FindResource("PromotionList")).Source = promotionList;

            _isAProductListViewSource = (CollectionViewSource)FindResource("IsAProductList");
            ProductGroup_CurrentChanged(null, null);
            Product_CurrentChanged(null, null);

            _productComponentViewSource = (CollectionViewSource)FindResource("ProductComponents");

            // Initialize the Misc tab
            var miscLines = from c in _context.tblMiscDefs
                            where c.TableName == "tblProduct" &&
                                (c.OwnerID == null || c.OwnerID == OwnerID)
                            select new { c.Name, c.Tooltip, c.FieldNumber };
            int miscCt = 0;
            foreach (var item in miscLines)
            {
                GridMisc.RowDefinitions.Add(new RowDefinition());
                Label lbl = new Label();
                lbl.Content = item.Name;
                lbl.ToolTip = item.Tooltip;
                GridMisc.Children.Add(lbl);
                Grid.SetRow(lbl, miscCt);
                Grid.SetColumn(lbl, 0);

                TextBox tb = new TextBox();
                Binding b = new Binding("UserDefined" + item.FieldNumber.ToString());
                tb.SetBinding(TextBox.TextProperty, b);
                GridMisc.Children.Add(tb);
                Grid.SetRow(tb, miscCt);
                Grid.SetColumn(tb, 1);

                miscCt++;
            }

            //_productGroupViewSource.Source = _context.tblProductGroups;
            //gridMain.DataContext = _productGroupViewSource;
            //this.DataContext = _productGroupViewSource;
            //this.DataContext = _context.tblProductGroups;

            //Binding b = new Binding();
            //b.Mode = BindingMode.OneWay;
            ////b.Source = _context.tblProductGroups;
            //b.Source = _productGroupViewSource;
            //b.Path = new PropertyPath("tblProduct", new Object[] {});
            ////listViewProducts.SetBinding(ListView.ItemsSourceProperty, b);
        }

        void Product_CurrentChanged(object sender, EventArgs e)
        {
            if (_productViewSource.View.CurrentItem != null)
            {
                _resultantProductPricing.Source = _context.spProductPricing(((tblProduct)_productViewSource.View.CurrentItem).ProductID, null, null);
            }
        }

        void ProductGroup_CurrentChanged(object sender, EventArgs e)
        {
            //int productGroupID = (int)_productGroupViewSource.View.CurrentItem.GetType().GetProperties()[0].GetValue(_productGroupViewSource.View.CurrentItem, null);
            int productGroupID = (int)comboProductGroup.SelectedValue;
            var isAProductList = (from c in _context.tblProducts
                                  where c.ActiveItem && !c.SalableItem && !c.InventoryItem && c.ProductGroupID == productGroupID
                                  orderby c.ShortName
                                  select new { ProductID = (int?)c.ProductID, ShortName = c.ShortName }).ToList();
            isAProductList.Add(new { ProductID = (int?)null, ShortName = "" });
            _isAProductListViewSource.Source = isAProductList;
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _context.Log = Console.Out;
                _context.SubmitChanges();
                this.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show("Error saving changes\n" + err.Message, "Error!");
            }
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnAddToPlan_Click(object sender, RoutedEventArgs e)
        {
            int productGroupID = (int)comboProductGroup.SelectedValue;
            int productID = (int)listViewProducts.SelectedValue;
            var containsProductList = from c in _context.tblProducts
                                      where c.ActiveItem && c.ProductGroupID == productGroupID 
                                        && c.ProductID != productID
                                        && !(from p in ((tblProduct)listViewProducts.SelectedItem).ProductComponents
                                             select p.ComponentProductID).Contains(c.ProductID)
                                      orderby c.ItemCode
                                      select new { c.ProductID, c.ShortName, c.ItemCode, c.LongName };

            ProductList dlg = new ProductList(containsProductList);
            if ((bool)dlg.ShowDialog())
            {
                tblProduct selectedProduct = (tblProduct)listViewProducts.SelectedItem;

                tblProductComponent newComponent = (tblProductComponent)((IEditableCollectionView)_productComponentViewSource.View).AddNew();
                //tblProductComponent newComponent = new tblProductComponent();
                newComponent.Qty = 1;
                newComponent.ComponentProductID = dlg.ProductID;
                selectedProduct.ProductComponents.Add(newComponent);
                newComponent.ContainsProduct = _context.tblProducts.Single(p => p.ProductID == dlg.ProductID);
                newComponent.ParentProduct = selectedProduct;
                ((IEditableCollectionView)_productComponentViewSource.View).CommitNew();
            }
        }

        private void btnRemoveFromPlan_Click(object sender, RoutedEventArgs e)
        {
            _context.tblProductComponents.DeleteOnSubmit((tblProductComponent)gridBuildPlan.SelectedItem);
        }

    }

}
